<template>
  <page-container :title="false" :breadcrumb="false">
    <div class="box-container">
      <a-form-model layout="inline" :model="queryParams">
        <a-form-model-item label="用户账号">
          <a-input v-model="queryParams.loginCode" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="用户姓名">
          <a-input v-model="queryParams.userName" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="用户部门">
          <a-tree-select v-model="queryParams.userOrg" style="width: 180px" placeholder="请选择部门" :tree-data="treeDept" :replace-fields="treeProps" allow-clear />
        </a-form-model-item>
        <a-form-model-item>
          <a-button
            icon="search"
            html-type="submit"
            @click="getTableDataByFirst"
          >
            查询
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>

    <div class="mt10">
      <div class="table_title_operate">
        <div class="left">
          <a-button
            type="primary"
            plain
            @click="onOpenAddUserModal"
          >新增用户</a-button>
        </div>
        <div class="right">
          <a-button
            type="danger"
            @click="onDeleteUsers"
          >批量删除</a-button>

          <a-button
            class="ml10"
            type="warning"
            @click="onExport"
          >导出</a-button>
        </div>
      </div>

      <s-table
        ref="table"
        class="bg-white"
        row-key="id"
        :columns="tableParams.columns"
        :data="tableParams.loadData"
        :row-selection="{ selectedRowKeys: tableParams.rowSelection.selectedRowKeys, onChange: tableParams.rowSelection.onChange }"
        :init-request="tableParams.initRequest"
        :pagination="tableParams.pagination"
      >
        <span slot="status" slot-scope="text">
          <a-badge v-if="text === 'ENABLE'" status="success" text="启用" />
          <a-badge v-else status="error" text="停用" />
        </span>
        <span slot="operate" slot-scope="text, record, index">
          <template>
            <a @click="onOpenModifyUserModal(index, record)">修改</a>
            <a-divider type="vertical" />
            <a @click="onDeleteUser(index, record)">删除</a>
            <a-divider type="vertical" />
            <a @click="onResetPassword(index, record)">重置密码</a>
          </template>
        </span>
      </s-table>
    </div>

    <a-modal v-model="open" :title="title">
      <a-form-model ref="userForm" :model="userForm" :rules="userFormRules">
        <a-row>
          <template v-if="userForm.id === undefined">
            <a-col :span="12">
              <a-form-item prop="loginCode" label="用户账号" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
                <a-input v-model="userForm.loginCode" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item prop="positionName" label="用户密码" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
                <a-input v-model="userForm.password" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :span="12">
            <a-form-item prop="userName" label="用户姓名" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="userForm.userName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item prop="userOrg" label="部门名称" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-tree-select v-model="userForm.userOrg" :tree-data="treeDept" :replace-fields="treeProps" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item prop="userPosition" label="职位名称" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-select v-model="userForm.userPosition">
                <a-select-option v-for="post in post_code_list" :key="post.id" :value="post.id">{{ post.positionName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item prop="userRole" label="角色名称" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-select v-model="userForm.userRole" mode="multiple">
                <a-select-option v-for="role in role_code_list" :key="role.id" :value="role.id">{{ role.roleName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="数据范围" :label-col="{ span: 4 }" :wrapper-col="{span:20}">
              <a-tree
                v-if="open"
                ref="menu"
                :checked-keys="deptTreeSelectedKeys"
                style="border: 1px solid #DCDFE6"
                checkable
                :tree-data="treeDept"
                :replace-fields="treeProps"
                @check="onChangeMenuTreeChecked"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系方式" prop="mobile" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="userForm.mobile" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="电子邮箱" prop="email" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="userForm.email" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户性别" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-radio-group v-model="userForm.sex">
                <a-radio v-for="item in genderList" :key="item.id" :value="item.dictValue">{{ item.dictLabel }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="账号状态" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-radio-group v-model="userForm.status">
                <a-radio v-for="item in stateTypeList" :key="item.id" :value="item.dictValue">{{ item.dictLabel }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="备注" :label-col="{ span: 4 }" :wrapper-col="{span:20}">
              <a-input v-model="userForm.remark" type="textarea" :rows="3" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form-model>

      <template slot="footer">
        <a-button key="back" @click="open = false">
          取消
        </a-button>

        <template v-if="!userForm.id">
          <!--新增-->
          <a-button key="submit" type="primary" @click="onAddOrModifyUser">确认</a-button>
        </template>
        <template v-else>
          <!--修改-->
          <a-button key="submit" type="primary" @click="onAddOrModifyUser">确认</a-button>
        </template>

      </template>
    </a-modal>
  </page-container>
</template>

<script>

import { parseTime, debounce, deleteNullChildren, getTreeBaseData, getArrIntersection } from '@/utils'
import { getPostByParamsApi } from '@/api/system/post'
import { getRoleByParamApi } from '@/api/system/role'
import { getDeptTreeApi } from '@/api/system/dept'
import { addUserApi, modifyUserApi, getUserListApi, deleteUserApi, deleteUsersApi, resetUserPasswordApi, exportUserApi } from '@/api/system/user'
import { userName, mailbox, telephone, userLoginCode } from '@/api/verification'

export default {
  name: 'User',
  data() {
    const columns = [
      {
        title: '用户账号',
        dataIndex: 'loginCode'
      },
      {
        title: '用户姓名',
        dataIndex: 'userName'
      },
      {
        title: '部门',
        dataIndex: 'userOrgName'
      },
      {
        title: '联系方式',
        dataIndex: 'mobile'
      },
      {
        title: '账号状态',
        dataIndex: 'status',
        scopedSlots: { customRender: 'status' }
      },
      {
        title: '操作',
        dataIndex: 'operate',
        scopedSlots: { customRender: 'operate' }
      }
    ]

    return {
      // pcode
      stateTypeList: [],
      genderList: [],

      value: '',

      queryParams: {
        userName: undefined,
        loginCode: undefined,
        userOrg: undefined
      },

      title: '',
      open: false,
      userForm: {},
      userFormRules: {
        userOrg: [{ required: true, message: '请选择用户部门', trigger: 'blur' }], // 部门id
        userRole: [{ required: true, message: '请选择用户角色', trigger: 'blur' }], // 用户角色
        loginCode: [
          { required: true, message: '请输入英文或数字组成的账号', trigger: 'blur' }, { validator: this.checkLogin }
        ], // 登录Id
        userName: [
          { required: true, message: '请输入正确的名称' }, { trigger: 'blur', validator: this.checkUserName }
        ], // 用户昵称
        mobile: [
          { required: false, message: '请输入正确的名称' }, { trigger: 'blur', validator: this.phone }
        ], // 手机号
        email: [
          { required: false, message: '请输入正确的邮箱账号', trigger: 'blur' }, { validator: this.emile }
        ], // 邮箱
        userPosition: [
          { required: true, message: '请选择用户职位', trigger: 'blur' }
        ] // 职位
      },
      post_code_list: [], // 职位列表
      role_code_list: [], // 角色列表
      treeDept: [], // 部门树
      deptTreeSelectedKeys: [],
      selectedDeptIds: [],
      treeProps: {
        key: 'id',
        title: 'name',
        children: 'children',
        value: 'id'
      },

      tableParams: {
        pagination: {
          showTotal: total => `共 ${total} 条`,
          showQuickJumper: true,
          pageSizeOptions: ['5', '10', '15', '20']
        },
        columns,
        loadData: parameter => {
          const requestParameters = Object.assign({}, parameter, this.$parseQueryParams(this.queryParams))
          return getUserListApi(requestParameters)
            .then(res => {
              return {
                ...res.data,

                dataList: deleteNullChildren(res.data.dataList)
              }
            })
        },
        rowSelection: {
          selectedRowKeys: [],
          onChange: this.onSelectChange
        },
        selectedRowKeys: [],
        selectedRows: [],
        initRequest: true
      }
    }
  },
  created() {
    this.initDict()
    this.getTableDataByFirst()
    getDeptTreeApi({}).then((res) => {
      if (res && res.code === 'A00000') {
        this.treeDept = this.$deleteNullChildren(res.data)
      }
    })
  },
  methods: {
    // 校验用户姓名
    checkUserName(rule, value, callback) {
      if (userName(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的用户姓名'))
      }
    },
    // 校验用户账号非中文
    checkLogin(rule, value, callback) {
      if (userLoginCode(value)) {
        callback()
      } else {
        callback(new Error('请输入英文或数字'))
      }
    },
    // 校验手机号
    phone(rule, value, callback) {
      if (!value || telephone(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的手机号码'))
      }
    },
    // 校验邮箱
    emile(rule, value, callback) {
      if (!value || mailbox(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱账号'))
      }
    },
    getTableDataByFirst() {
      this.$refs.table && this.$refs.table.refresh(true)
    },

    /**
     * 初始化数据字典
     */
    initDict() {
      this.$getCodeDictMap(this, {
        STATUS_TYPE: 'stateTypeList',
        GENDER: 'genderList'
      })
    },

    /**
     * 重置用户添加或修改表单
     */
    resetUserForm() {
      this.userForm = {
        id: undefined,
        userOrg: undefined, // 部门id
        loginCode: undefined, // 登录Id
        password: '88888888', // 密码
        userName: undefined, // 用户昵称
        mobile: undefined, // 手机号
        email: undefined, // 邮箱
        sex: 'MAN', // 性别
        avatar: undefined, // 头像
        status: 'ENABLE', // 用户状态
        userPosition: undefined, // 职位
        remark: undefined, // 备注
        userRole: [], // 角色ids
        dataScope: [] // 数据范围
      }

      // this.$resetForm('userForm')
    },

    /**
     * 打开新增表单弹窗
     */
    onOpenAddUserModal() {
      this.resetUserForm()

      getPostByParamsApi().then((res) => {
        if (res && res.code === 'A00000') {
          this.post_code_list = res.data
        }
      })

      getDeptTreeApi({}).then((res) => {
        if (res && res.code === 'A00000') {
          this.treeDept = this.$deleteNullChildren(res.data)
        }
      })

      getRoleByParamApi({}).then((res) => {
        if (res && res.code === 'A00000') {
          this.role_code_list = res.data
        }
      })

      this.title = '创建用户'
      this.open = true
    },

    /**
     * 打开修改表单弹窗
     * @param index 当前角色数组索引
     * @param post 当前角色信息
     */
    onOpenModifyUserModal(index, user) {
      this.resetUserForm()

      getPostByParamsApi().then((res) => {
        if (res && res.code === 'A00000') {
          this.post_code_list = res.data
        }
      })

      getDeptTreeApi({}).then((res) => {
        if (res && res.code === 'A00000') {
          this.treeDept = this.$deleteNullChildren(res.data)
        }
      })

      getRoleByParamApi({}).then((res) => {
        if (res && res.code === 'A00000') {
          this.role_code_list = res.data

          this.userForm = { ...user }
          this.title = '修改用户'
          this.open = true
          this.$nextTick(() => {
            const subTree = getTreeBaseData(this.treeDept)

            this.deptTreeSelectedKeys = getArrIntersection(user.dataScope, subTree)

            this.selectedMenuIds = user.dataScope
          })
        }
      })
    },

    onChangeMenuTreeChecked(node, event) {
      this.selectedDeptIds = [...node, ...event.halfCheckedKeys]
      // this.menuIds = node.join(',').concat(',').concat(event.halfCheckedKeys.join(','))
      this.deptTreeSelectedKeys = node
    },

    /**
     * 新增或修改用户信息
     */
    onAddOrModifyUser: debounce(function() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          const params = {
            id: this.userForm.id,
            userOrg: this.userForm.userOrg,
            password: this.userForm.id ? undefined : this.userForm.password,
            loginCode: this.userForm.id ? undefined : this.userForm.loginCode,
            userName: this.userForm.userName,
            email: this.userForm.email,
            mobile: this.userForm.mobile,
            sex: this.userForm.sex,
            avatar: this.userForm.avatar,
            status: this.userForm.status,
            remark: this.userForm.remark,
            userRole: this.userForm.userRole,
            userPosition: this.userForm.userPosition,
            dataScope: this.selectedDeptIds
          }
          // 新增用户
          if (this.userForm.id === undefined) { // 新增岗位
            addUserApi(params).then((res) => {
              if (res && res.code === 'A00000') {
                this.open = false
                this.$message.success(res.msg)
                this.getTableDataByFirst()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else { // 修改角色
            // 修改部门
            modifyUserApi(params).then((res) => {
              if (res && res.code === 'A00000') {
                this.open = false
                this.$message.success(res.msg)
                this.getTableDataByFirst()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    }),

    /**
     * 删除用户
     */
    onDeleteUser(index, user) {
      this.$confirm({
        title: '提示',
        content: '确认删除当前用户, 是否继续?',
        okText: '确定',
        cancelText: '取消',
        type: 'warning',
        onOk: () => {
          const params = {
            id: user.id
          }
          deleteUserApi(params).then((res) => {
            if (res && res.code === 'A00000') {
              this.$message.success(res.msg)
              this.getTableDataByFirst()
            }
          })
        }
      })
    },

    /**
     * 批量删除用户
     */
    onDeleteUsers() {
      const userIds = this.tableParams.rowSelection.selectedRowKeys
      if (userIds.length === 0) {
        this.$message.warning('请选择用户')
        return
      }

      this.$confirm({

        title: '提示',
        content: '确认批量删除, 是否继续?',
        okText: '确定',
        cancelText: '取消',
        type: 'warning',
        onOk: () => {
          deleteUsersApi(userIds).then((res) => {
            if (res && res.code === 'A00000') {
              this.$message.success(res.msg)
              this.getTableDataByFirst()
            }
          })
        }
      })
    },

    /**
     * 重置密码
     */
    onResetPassword(index, user) {
      this.$confirm({
        title: '提示',
        content: '确认重置当前用户的密码, 是否继续?',
        okText: '确定',
        cancelText: '取消',
        type: 'warning',
        onOk: () => {
          const params = {
            id: user.id
          }
          resetUserPasswordApi(params).then((res) => {
            if (res && res.code === 'A00000') {
              this.$message.success(res.msg)
            }
          })
        }
      })
    },

    /**
     * 导出用户
     */
    onExport: debounce(function() {
      const userIds = this.tableParams.rowSelection.selectedRowKeys
      if (userIds.length === 0) {
        this.$message.warning('请选择用户')
        return
      }

      exportUserApi(userIds).then((res) => {
        if (res) {
          this.$exportFile('用户.xls', [res])

          this.$refs.table.clearSelected()
        }
      })
    }),

    /**
     * 表格多选示例
     * @param selectedRowKeys
     * @param selectedRows
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.tableParams.rowSelection.selectedRowKeys = selectedRowKeys

      // this.tableParams.selectedRowKeys = selectedRowKeys
      // this.tableParams.selectedRows = selectedRows
    }
  }
}
</script>

<style scoped>
/** 全局表格头部操作 */
.table_title_operate{
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

</style>
